function parseCookie(varName)
{
	var srcCookie = window.document.cookie;

	if( srcCookie == "" )
	{
		return "";
	}

	var nPos = srcCookie.lastIndexOf(varName+"=");
	
	if( nPos > 0 )
	{
		if( nPos >= 2 )
		{
			nPos = srcCookie.indexOf("; "+varName+"=",nPos-2);
		}
		else
		{
			nPos = srcCookie.indexOf("; "+varName+"=");
		}
	}

	if( nPos >= 0 )
	{
		nPos = srcCookie.indexOf('=',nPos)+1;

		var nTailPos = srcCookie.indexOf("; ",nPos);
		
		if( nTailPos > 0 )
		{
			return srcCookie.substring(nPos,nTailPos);
		}
		else
		{
			return srcCookie.substr(nPos);
		}
	}

	return "";
}

function formatNum(str)
{
	if( !isNaN(str) )
	{
		str = str.toString();
	}

	var newStr = "";

	var count = 0;

	if( str.indexOf(".") == -1 )
	{
		for( var i = (str.length-1); i >= 0; i-- )
		{
			if( count % 3 == 0 && count != 0 )
			{
				newStr = str.charAt(i) + "," + newStr;
			}
			else
			{
				newStr = str.charAt(i) + newStr;
			}

			count++;
		}

		str = newStr;
	}
	
	return str;
}

function searchPHPSay()
{
	var word = $.trim($('input[name=q]').val().replace(/<\/?[^>]*>/g,''));

	$('input[name=q]').val(word);

	if( word.length < 2 || word.length > 15 )
	{
		alertMessage("输入字符长度范围：2～15");

		$('input[name=q]').focus();
		
		return false;
	}
}

function clearSearchHistory()
{
	document.cookie = "search_history=";

	$("#search-history").slideUp();
}

function loadSearchHistory()
{
	var words = parseCookie("search_history");

	if( words != "" )
	{
		words = $.parseJSON(decodeURIComponent(decodeURIComponent(words)));

		for(var i = 0; i < words.length; i++)
		{
			words[i] = words[i].replace(/<\/?[^>]*>/g,'');

			$("#search-history .text-items").append('<li><a href="./search.php?q='+encodeURIComponent(words[i])+'">'+words[i]+'</a></li>');
		}

		$("#search-history").show();
	}
}

function goSignIn()
{
	location.href = "./passport.php?return=" + encodeURIComponent(location.pathname + location.search);

	return false;
}

function openURL(a)
{
	window.open(a.innerHTML);
}

function hideDropdownMenu()
{
	$(window).unbind("click",hideDropdownMenu);

	$(".dropdown-menu").hide();
}

function rightNavBind()
{
	$("#settings").click(function()
	{
		if( $(".dropdown-menu").is(":hidden") )
		{
			$(window).click(hideDropdownMenu);

			$(".dropdown-menu").show();
		}
		else
		{
			hideDropdownMenu();
		}

		return false;
	});

	$(".write-btn").click(function()
	{
		if( location.pathname.replace("index.php","").substr(-1) == "/" )
		{
			showWriteTopic();
		}
		else
		{
			location.href = "./#write";
		}

		return false;
	});
}

function alertMessage(msg)
{
	$(".alert-messages .message .message-text").html(msg);

	if ( $(".alert-messages").is(":visible") )
	{
		return false;
	}

	$(".alert-messages").fadeIn(300);

	$('<span class="web-icon icon-close"></span>').appendTo(".alert-messages .message").click(hideAlert);

	setTimeout(hideAlert,2000);
}

function hideAlert()
{
	var o = $(".alert-messages .message .icon-close");

	o.parent().parent().fadeOut(300,function(){
		o.remove();
	});
}

function notificationRequest()
{
	if ( ("Notification" in window) )
	{
		if ( Notification.permission !== "granted" )
		{
			Notification.requestPermission(function()
			{
				location.href = "notification.php";
			});

			return false;
		}
	}

	location.href = "notification.php";

	return false;
}

function showNotifications()
{
	$(".notify-count").click(notificationRequest);

	if( window.location.pathname.indexOf("/notification.php") >= 0 )
	{
		return false;
	}

	$.post("post.php",{"do":"getNotify"},function(data)
	{
		$(".notify-count strong").html(data.count);

		if( parseInt(data.count) > 0 )
		{
			$(".new-count .count-inner").html(data.count).parent().show();

			if( parseCookie("notifyCount") == data.count )
			{
				return false;
			}

			if( ("Notification" in window) )
			{
				if( Notification.permission === "granted" )
				{
					var message = data.result+" ";

					if( data.result.split(", ").length > 1 )
					{
						message += "等人";
					}

					message += "提到了您。";

					var n = new Notification("您有 "+data.count+" 条未读提醒", {body:message,tag:"PHPSayNotification",icon:"mobile_static/apple-touch-icon.png"});

					n.onclick = function() {this.close();window.open('./notification.php','PHPSayNotification');};

					n.onshow = function () {setTimeout(n.close.bind(n), 5000);}
				}
			}
		}

		document.cookie = "notifyCount = " + data.count;

	},"json");
}

function imageZoom(img)
{
	$('<div id="imageZoomMask"></div>').appendTo(document.body).css({position:'absolute',top:0,left:0,'z-index':2002,width:$(document).width(),height:$(document).height(),'background':'#000','opacity':'0.8'}).click(function(){$("#imageZoomMask").remove();$("#imageZoomContent").remove();});

	$('<div id="imageZoomContent"></div>').appendTo(document.body).css({position:'absolute',top:'45px',left:'50%','z-index':2003,cursor:"pointer"}).click(function(){$("#imageZoomMask").remove();$("#imageZoomContent").remove();});

	$("#imageZoomContent").append($('<img src="'+img+'" style="max-width:'+($("#imageZoomMask").width()-300)+'px;max-height:'+($("#imageZoomMask").height()-160)+'px;" />').hide().load(function()
	{
		var margin_top = $(window).scrollTop();

		if( $(this).height() < $(window).height() )
		{
			margin_top = ($(window).height()-$(this).height())/2 - 30 + margin_top;
		}

		$(this).parent().css({'margin-top':margin_top+"px",'margin-left':-($(this).width()/2)+"px"});

		$(this).fadeIn();
	}));
}

function textCounter(maxlen) {
	var textArray = $('textarea[name=message]').val().replace(/\r/,"").split("\n");
	var arrayLen = textArray.length;
	if (arrayLen > 1) {
		var textString = "";
		for (var i=0;i<arrayLen;i++) {
			if ($.trim(textArray[i]) != "") {
				textString += textArray[i].replace(/　　/,"");
				if (i < (arrayLen-1)) {
					textString += "\n";
				}
			}
		}
		$('textarea[name=message]').val(textString);
	}
	var len = $.trim($('textarea[name=message]').val()).length;
	if (len < 1) {
		if ($(".submit-button").attr("disabled") != "disabled" && $(".submit-button").attr("data") == "text") {
			$(".submit-button").attr("disabled","disabled");
		}
	} else if ( len > maxlen ) {
		if ($(".submit-button").attr("disabled") != "disabled") {
			$(".submit-button").attr("disabled","disabled");
		}		
	} else {
		if ($(".submit-button").attr("disabled") == "disabled") {
			$(".submit-button").removeAttr("disabled");
		}
	}
	len = maxlen - len;
	$(".text-counter").html(len);
	if (len < 11) {
		$(".text-counter").css("color","#D40D12");
		return false;
	}
	if (len < 21) {
		$(".text-counter").css("color","#5C0002");
		return false;
	}
	$(".text-counter").css("color","#999999");
}

function showWriteTopic()
{
	$("body").css({overflow:"hidden"});

	$(".writeTopic").css({"width":$(document).width(),"height":$(document).height()}).fadeIn(100);

	$(".writeTopic .addtopic").css({"top":$(window).scrollTop()+($(window).height()/2)-($(".writeTopic .addtopic").height()/2)});

	$(".alert-messages .message").css({"border-radius":"6px"});
}

function checkFileExtendIsImage(str)
{
	var re = new RegExp("(.jpg|.png|.gif|.jpeg)$");

	if ( re.test(str.toLowerCase()) )
	{
		return true;
	}

	return false;
}

function pictureOnChange() {
	$("#picture").live('change',function() {
		if (!window.FileReader) {
			$(this).val("");
			alertMessage("您的浏览器不能上传图片");
			return false;
		}
		if (!this.files[0].type.match(/^(image\/gif|image\/jpeg|image\/png)$/i) && !checkFileExtendIsImage($(this).val())) {
			$(this).val("");
			alertMessage("只能上传 JPEG | PNG | GIF 格式的图片");
			return false;
		}
		if (this.files[0].size > 5242880) {
			$(this).val("");
			alertMessage("图片不能超过5MB");
			return false;
		}
		if ($(".picture-preview > img").size() > 8) {
			$(this).val("");
			alertMessage("最多只能上传9张图片");
			return false;
		}
		var upImgId = encodeURIComponent("upImg_" + this.files[0].name.replace() + this.files[0].lastModified).replace(/[^a-zA-Z_0-9]/g,"");
		if ($("#"+upImgId).length > 0) {
			$(this).val("");
			alertMessage("图片已存在");
			return false;
		}
		var reader = new FileReader();
		reader.onload = function(e) {
			$(".picture-preview").append("<img id='"+upImgId+"' src='data:application/octet-stream;"+e.target.result.substr(e.target.result.indexOf("base64,"))+"' />");
			$("#"+upImgId).click(function() {
				$(this).remove();
				if ($(".picture-preview").html() == "") {
					$(".submit-button").attr("data","text");
				}
				textCounter(2000);
			});
			$(".submit-button").removeAttr("disabled").attr("data","media");
		}
		reader.readAsDataURL(this.files[0]);
		$(this).val("");
	});
}

function showIpLocation()
{
	var obj = $(this);

	obj.attr("data","");

	if( obj.attr("data-address") != undefined )
	{
		insertLocation(obj,obj.attr("data-address"));

		return false;
	}

	var ip = obj.attr("data-ip");

	var address = "未知地区";

	if( ip == "" )
	{
		insertLocation(obj,address);

		return false;
	}

	$.post("location.php",{"do":"ip2address","ip":ip},function(data){

		if( data.result == "success" )
		{
			if( data.address != "" )
			{
				address = data.address;
			}
		}

		insertLocation(obj,address);

	},"json");
}

function showLocation()
{
	var obj = $(this);

	obj.attr("data","");

	if( obj.attr("data-address") != undefined )
	{
		insertLocation(obj,obj.attr("data-address"));

		return false;
	}

	var gps = obj.attr("data-gps").split(",");

	var address = "中国以外地区";

	if( GPS.outOfChina(Number(gps[0]),Number(gps[1])) )
	{
		insertLocation(obj,address);

		return false;
	}

	var gmap = GPS.gcj_encrypt(Number(gps[0]),Number(gps[1]));

	var bmap = GPS.bd_encrypt(gmap.lat,gmap.lon);

	$.post("location.php",{"do":"gps2address","gps":bmap.lat+","+bmap.lon},function(data){

		if( data.result == "success" )
		{
			address = ( data.address != "" ) ? data.address+"附近" : "未知";
		}
		else
		{
			address = "未知位置";
		}

		insertLocation(obj,address);

	},"json");
}

function insertLocation(obj,address)
{
	obj.attr("data-address",address);

	if( obj.attr("data") == undefined )
	{
		return false;
	}

	obj.after('<div class="location-info">'+address+'</div><div class="location-arrow-bottom"></div>');

	obj.next().css({"top":-obj.next().height()-23,"right":-obj.next().width()/2-2});
}

function hideLocation()
{
	$(this).removeAttr("data");

	$(".location-info").remove();

	$(".location-arrow-bottom").remove();
}

function postReplyTopic(isquick)
{
	if( parseCookie('phpsay_secure') == "" )
	{
		alertMessage("请先登录");

		return false;
	}

	var msg = $.trim($('#reply-form textarea[name=message]').val());

	var picture = [];

	$(".picture-preview img").each(function() {
		picture.push($(this).attr("src"));
	});

	$("#reply-form .submit-button").attr("disabled","disabled");

	$.post("post.php",{"do":"replyTopic","tid":$('#reply-form input[name=tid]').val(),"msg":msg,"picture":picture},function(data)
	{
		if (data.result == "success")
		{
			if (!isquick)
			{
				$("#reply-form .submit-button").attr("data","text");

				$("#reply-form .picture-preview").html("");

				$('#reply-form textarea[name=message]').val('');

				$("#reply-form .text-counter").html("2000");

				$(".reply-items").append(data.message);

				$(".reply-items li:last .icon-like").css({"color":"#E1E8ED","cursor":"default"});

				if( $(".reply-items li:last .icon-location").length > 0 )
				{
					$(".reply-items li:last .icon-location").hover(showLocation,hideLocation);
				}

				if( $(".reply-items li:last .icon-ip").length > 0 )
				{
					$(".reply-items li:last .icon-ip").hover(showIpLocation,hideLocation);
				}

				$("html,body").animate({scrollTop: $(".reply-item:last").offset().top}, 500);
			}
			else
			{
				$(".stream-items .stream-item .quickreply-form").slideUp(function()
				{
					$(this).prev().unbind().click(quickReply);

					$(this).remove();
				});
			}

			$('.balance-count strong').html((parseInt($('.balance-count strong').html())+parseInt(data.balance)));

			alertMessage("回复成功");
		}
		else
		{
			if( $.trim($('#reply-form textarea[name=message]').val()).length >= 1 || $("#picture").val() != "" )
			{
				$("#reply-form .submit-button").removeAttr("disabled");
			}

			if (data.result == "login")
			{
				alertMessage("请先登录");
			}
			else if (data.result == "error")
			{
				alertMessage(data.message);
			}
			else
			{
				alertMessage("服务器异常");
			}
		}

	},"json");
}

function checkIsGoOn(ev)
{
	var target = ev.target || ev.srcElement;

	var tag = target.tagName;

	if ( tag )
	{
		if( tag.toLowerCase() === 'p' || tag.toLowerCase() === 'div' )
		{
			return true;
		}
	}

	return false;
}

function quickReply(ev)
{
	if ( checkIsGoOn(ev) )
	{
		$(".stream-items .stream-item .quickreply-form").slideUp(function()
		{
			$(this).prev().removeAttr("style").unbind().click(quickReply);

			$(this).remove();
		});

		$(this).attr("style","background-color:#FFF");

		var replyArray = $(this).attr("data").split("@");

		var quickReplyForm = $("#quickreply-form").html();
		
		if( parseInt(replyArray[1]) > 0 )
		{
			quickReplyForm = quickReplyForm.replace("[tid]",replyArray[1]);
		}
		else
		{
			quickReplyForm = quickReplyForm.replace("[nickname]",replyArray[0]);
		}

		$(this).unbind().after(quickReplyForm).next().slideDown(function(){

			$("#reply-form textarea[name=message]").focus();

			if( parseInt(replyArray[1]) > 0 )
			{
				$("#reply-form textarea[name=message]").val('@'+replyArray[0]+' ');

				$("#reply-form .submit-button").removeAttr("disabled");
			}

			if( parseInt(replyArray[1]) > 0 )
			{
				$("#reply-form textarea[name=message]").keyup(function(){textCounter(2000);});
			}
			else
			{
				$("#reply-form textarea[name=message]").keyup(function(){textCounter(200);});
			}
			
			$("#reply-form .submit-button").click(function()
			{
				if( parseInt(replyArray[1]) > 0 )
				{
					postReplyTopic(true);
				}
				else
				{
					postPrivateMessage(true);
				}

				return false;
			});
			
			$(this).prev().click(function(event)
			{
				if ( checkIsGoOn(event) )
				{
					$(this).removeAttr("style").next().slideUp(function(){

						$(this).prev().unbind().click(quickReply);

						$(this).remove();
					});
				}
			});
		});
	}
}

function postPrivateMessage(isreply)
{
	$(".submit-button").attr("disabled","disabled");

	$('textarea[name=message]').attr("disabled","disabled");

	$.post("post.php",{"do":"addPrivateMessage","nickname":$('input[name=nickname]').val(),"msg":$.trim($('textarea[name=message]').val())},function(data)
	{
		if (data.result == "success")
		{
			if( isreply )
			{
				$(".stream-items .stream-item .quickreply-form").slideUp(function()
				{
					$(this).prev().unbind().click(quickReply);

					$(this).remove();
				});

				$('.balance-count strong').html((parseInt($('.balance-count strong').html())+parseInt(data.balance)));

				alertMessage("私信回复成功");
			}
			else
			{
				alertMessage("私信发送成功");

				setTimeout(function(){location.href=location.href},1000);
			}
		}
		else
		{
			if (data.result == "login")
			{
				alertMessage("请先登录");
			}
			else if (data.result == "error")
			{
				alertMessage(data.message);
			}
			else
			{
				alertMessage("服务器异常");
			}
		}

		$('textarea[name=message]').removeAttr("disabled");

	},"json");

	return false;
}

function replyAt(uname)
{
	var regExp = new RegExp("@"+uname+" ", 'gi');

	$('#reply-form textarea[name=message]').val($('#reply-form textarea[name=message]').val().replace(regExp,"")+"@"+uname+" ").focusEnd();

	$("html,body").animate({scrollTop: $(".reply-form").offset().top-42}, 300);

	textCounter(2000);
}

function deleteTopic(tid)
{
	$("#deleteTopic-"+tid).css({"color":"#996666"}).removeAttr("onclick").click(function()
	{
		$.post("post.php",{"do":"deleteTopic","tid":tid},function(data)
		{
			if ( data.result == "success" )
			{
				$("#item-"+tid).slideUp(300,function(){$(this).remove();alertMessage("删除成功");});
			}
			else
			{
				alertMessage(data.message);
			}

		},"json");
	});
}

function deleteReply(pid)
{
	$("#deleteReply-"+pid).css({"color":"#996666"}).removeAttr("onclick").click(function()
	{
		var o = $(this);

		o.hide();

		$.post("post.php",{"do":"deleteReply","pid":pid},function(data)
		{
			if (data.result == "success")
			{
				$("#item-"+pid).slideUp(300,function(){$(this).remove();alertMessage("删除成功");});
			}
			else
			{
				alertMessage(data.message);
			}

		},"json");
	});
}

function deleteNotification(nid)
{
	$("#deleteNotification-"+nid).css({"color":"#996666"}).removeAttr("onclick").click(function()
	{
		var o = $(this);

		o.hide();

		$.post("post.php",{"do":"deleteNotification","nid":nid},function(data)
		{
			if (data.result == "success")
			{
				$("#item-"+nid).slideUp(300,function(){$(this).remove();alertMessage("删除成功");});
			}
			else
			{
				alertMessage("删除失败");

				o.show();
			}

		},"json");
	});
}

function updateFavNum(num)
{
	var o = $(".favorite-count").children("strong");

	if (o.length > 0)
	{
		o.html(parseInt(o.html()) + num);
	}
}

function favTopic(tid)
{
	var o = $("#favTopic-"+tid);

	o.removeAttr("onclick");

	$.post("post.php",{"do":"favTopic","tid":tid},function(data)
	{
		if (data.result == "success")
		{
			o.removeClass("icon-fav").addClass("icon-faved").attr("onclick","unFavTopic("+tid+")").attr("title","取消收藏");

			if (data.message >= 1)
			{
				updateFavNum(1);
			}
		}
		else if (data.result == "login")
		{
			alertMessage("请先登录");
		}
		else
		{
			o.attr("onclick","favTopic("+tid+")");
			
			alertMessage("收藏失败");
		}
		
	},"json");
}

function unFavTopic(tid)
{
	var o = $("#favTopic-"+tid);

	o.removeAttr("onclick");

	$.post("post.php",{"do":"unFavTopic","tid":tid},function(data)
	{
		if (data.result == "success")
		{
			o.removeClass("icon-faved").addClass("icon-fav").attr("onclick","favTopic("+tid+")").attr("title","收藏");

			updateFavNum(-1);
		}
		else
		{
			o.attr("onclick","unFavTopic("+tid+")");

			alertMessage("取消收藏失败");
		}

	},"json");
}

function deleteFavTopic(tid)
{
	$("#item-"+tid+" .icon-trash").css({"color":"#996666"}).removeAttr("onclick").click(function()
	{
		var o = $(this);

		o.hide();

		$.post("post.php",{"do":"unFavTopic","tid":tid},function(data)
		{
			if (data.result == "success")
			{
				$("#item-"+tid).slideUp(200,function(){$(this).remove();});

				updateFavNum(-1);
			}
			else
			{
				alertMessage("取消收藏失败");

				o.show();
			}

		},"json");
	});
}

function blockUser(uid)
{
	$(".block").hide();

	$.post("post.php",{"do":"userGroup","uid":uid},function(data)
	{
		if (data.result == "success")
		{
			if(data.message == 1)
			{
				$(".block").removeClass("blocked");
			}
			else if(data.message == 0)
			{
				$(".block").addClass("blocked");
			}
		}
		else
		{
			alertMessage("操作异常");
		}

		$(".block").show();

	},"json");	
}

function rechargeOnline()
{
	$('<div></div>').appendTo(document.body).css({
		position:'absolute',
		top:0,
		left:0,
		'z-index':1000,
		width:$(document).width(),
		height:$(document).height(),
		'background':'#000 url(static/loading.gif) no-repeat',
		'background-position':'center center',
		'background-size':'32px 32px',
		'opacity':'0.8'
	});

	$('input[name=amount]').val($(this).attr("data"));

	setTimeout(function(){$('#checkout-form').submit();},500);
}
